package com.liang.blog.security.jwt;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @Author：YanWenLiang
 * @Date:2023-06-22-15:29
 */
public class JwtHelper {
    private static long tokenExpiration = 24 * 60 * 60 * 1000;
    private static String tokenSignKey = "qwertyuiopasdfghjklzxcvbnm";

    public static String createToken(Long userId, String account, String userKey) {
        String token = Jwts.builder()
                .setSubject("BLOG-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("account", account)
                .claim("userKey", userKey)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    public static Claims getClaims(String token){
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        return claimsJws.getBody();
    }

    public static Long getUserId(String token) {
        Integer userId = (Integer) getClaims(token).get("userId");
        return userId.longValue();
    }

    public static String getAccount(String token) {
        return (String) getClaims(token).get("account");
    }

    public static String getUserKey(String token){
        return (String) getClaims(token).get("userKey");
    }


    public static void main(String[] args) {
//        String token = JwtHelper.createToken(1L, "55");
//        System.out.println(token);
//        System.out.println(JwtHelper.getUserId(token));
//        System.out.println(JwtHelper.getUserName(token));

    }
}
